﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Hangjing.DBUtility;

/// <summary>
/// 商家结算
/// </summary>
public partial class Admin_shop_shopsettle : AdminPageBase
{
    private string SqlWhere
    {
        get
        {
            object o = ViewState["SqlWhere"];
            return (o == null) ? "" : Convert.ToString(o);
        }
        set
        {
            ViewState["SqlWhere"] = value;
        }
    }

    protected string ordersort
    {
        get
        {
            object o = ViewState["ordersort"];
            return (o == null) ? "unid" : Convert.ToString(o);
        }
        set
        {
            ViewState["ordersort"] = value;
        }
    }

    Custorder bll = new Custorder();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            WebUtility.SetDDLCity(DDLArea);

            initsql();



            new OrderState().BindOrderState(ddlOrderState);

            EnumHelper.OrderSourceToDropDownList(ddlsource);

            IList<DeliverInfo> delivers = SectionProxyData.GetDeliverList();
            if (UserHelp.GetAdmin().CityID != 0)
            {
                delivers = delivers.Where(a => a.Inve1 == UserHelp.GetAdmin().CityID).ToList();
            }
            //BindData(ordersort);
        }
    }

    /// <summary>
    /// 绑定指定的数据
    /// </summary>
    protected void BindData(string oo)
    {
        this.AspNetPager1.RecordCount = bll.GetCountFix(SqlWhere);

        IList<CustorderInfo> orders = bll.GetListFix(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, SqlWhere, "custorder.unid", 1);
        IList<DeliverGroupInfo> groups = SectionProxyData.GetEdelivergroupList();
        IList<CityInfo> citys = SectionProxyData.GetCityList();

        foreach (var item in orders)
        {
            foreach (var group in groups)
            {
                if (item.groupid == group.ID)
                {
                    item.FoodName = group.classname;
                }
            }
            item.cityname = "";
            foreach (var city in citys)
            {
                if (item.cityid == city.cid)
                {
                    item.cityname = city.cname;
                }
            }
            Hangjing.WebCommon.WebHelper.setSettleData(item);
        }

        this.rtpOrderlist.DataSource = orders;
        this.rtpOrderlist.DataBind();

        CustorderInfo count = bll.GetCountAndTotal1(SqlWhere);
        lborder.InnerText = count.OrderCount.ToString();
        lbcount.InnerText = count.Advance.ToString();
        lbsendfee.InnerText = count.shopdiscountmoney.ToString();
        this.lbadvance.InnerText =( count.shopdiscountmoney - count.Advance).ToString();

    }

    protected void initsql()
    {
        AlertScript.RegScript(this.Page, UpdatePanel1, "loading();");

        SqlWhere = " 1=1 and Custorder.delflag = 0 ";
        SqlWhere = new RightsTool().getOrderWhere(SqlWhere);
        if (!string.IsNullOrEmpty(HjNetHelper.GetQueryString("day")))
        {
            SqlWhere += " and  custorder.OrderDateTime between '" + DateTime.Now.ToShortDateString() + "' and  '" + DateTime.Now.ToString() + "'";
        }

        int shopid = HjNetHelper.GetQueryInt("tid", 0);
        if (shopid > 0)
        {
            SqlWhere += " and TogoId = " + shopid + " ";
        }

        if (tbreceiver.Text.Trim() != "")
        {
            SqlWhere += " and OrderRcver like '%" + WebUtility.InputText(tbreceiver.Text) + "%'";
        }
        if (tborderid.Text != "")
        {
            SqlWhere += " and orderid like '%" + WebUtility.InputText(tborderid.Text) + "%'";
        }
        if (tbTogoName.Text != "")
        {
            SqlWhere = SqlWhere + " and EXISTS (SELECT Unid FROM dbo.Points WHERE Unid = dbo.Custorder.TogoId AND Name LIKE '%" + WebUtility.InputText(tbTogoName.Text) + "%')";
        }
        if (tbphone.Text != "")
        {
            SqlWhere += " and  OrderComm like '%" + Utils.RegEsc(WebUtility.InputText(this.tbphone.Text.Trim())) + "%' ";
        }
        if (tbStartTime.Text != "")
        {
            SqlWhere = SqlWhere + " and  custorder.OrderDateTime >= '" + WebUtility.InputText(this.tbStartTime.Text) + "' ";
        }
        if (tbEndTime.Text != "")
        {
            SqlWhere = SqlWhere + " and  custorder.OrderDateTime <=  '" + WebUtility.InputText(this.tbEndTime.Text) + " 23:59:59'";
        }
        if (ddlOrderState.SelectedValue != "-1")
        {
            SqlWhere += " and OrderStatus = " + ddlOrderState.SelectedValue;
        }
        if (DDLArea.SelectedValue != "0")
        {
            SqlWhere += " and custorder.cityid = " + DDLArea.SelectedValue + "";
        }
        if (ddleatytpe.SelectedValue != "-1")
        {
            SqlWhere += " and ReveInt2 = " + ddleatytpe.SelectedValue;
        }
        if (ddlsource.SelectedValue != "-1")
        {
            SqlWhere += " and fromweb = " + ddlsource.SelectedValue;
        }

        if (ddlpaystate.SelectedValue != "-2")
        {
            SqlWhere += " and paystate=" + ddlpaystate.SelectedValue;
        }
        if (this.ddlpaymodel.SelectedValue != "-1")
        {
            SqlWhere = SqlWhere + " and paymode=" + ddlpaymodel.SelectedValue + "";
        }
        if (this.ddlIsShopSet.SelectedValue != "-1")
        {
            SqlWhere = SqlWhere + " and IsShopSet=" + ddlIsShopSet.SelectedValue + "";
        }
        if (tbdelivername.Text != "")
        {
            SqlWhere = SqlWhere + " and EXISTS (SELECT * FROM dbo.Deliver WHERE DataId = dbo.Custorder.deliverid AND Name LIKE '%" + WebUtility.InputText(tbdelivername.Text) + "%')";
        }
        if (tbgroup.Text != "")
        {
            SqlWhere = SqlWhere + " and deliverid in  (select dataid from deliver where GpsIMEI in (select id from DeliverGroup where classname LIKE '%" + WebUtility.InputText(tbgroup.Text) + "%'))";
        }
        if (tbinuse.Text.Trim() != "")
        {
            SqlWhere += " and custorder.inuse like '%" + WebUtility.InputText(tbinuse.Text) + "%'";

        }

        


        if (this.ddlisauth.SelectedValue != "-1")
        {
            SqlWhere += " and Commentstate = " + ddlisauth.SelectedValue;
        }
        if (this.ddlsettlecycle.SelectedValue != "-1")
        {
            SqlWhere += " and settlecycle = " + ddlsettlecycle.SelectedValue;
        }


        


        if (this.ddlisfile.SelectedValue != "-1")
        {
            SqlWhere += " and pointrat = " + ddlisfile.SelectedValue;
        }



        if (tbAddressText.Text.Trim() != "")
        {
            SqlWhere += " and AddressText like '%" + WebUtility.InputText(tbAddressText.Text) + "%'";

        }
        if (tbOrderAddress.Text.Trim() != "")
        {
            SqlWhere += " and OrderAddress like '%" + WebUtility.InputText(tbOrderAddress.Text) + "%'";

        }
        if (tbOrderAttach.Text.Trim() != "")
        {
            SqlWhere += " and OrderAttach like '%" + WebUtility.InputText(tbOrderAttach.Text) + "%'";

        }

        if (tbcardids.Text.Trim() != "")
        {
            SqlWhere += " and cardids like '%" + WebUtility.InputText(tbcardids.Text) + "%'";

        }
        if (tbshopauthuser.Text.Trim() != "")
        {
            SqlWhere += " and shopauthuser like '%" + WebUtility.InputText(tbshopauthuser.Text) + "%'";

        }
        if (tbshopfileuser.Text.Trim() != "")
        {
            SqlWhere += " and shopfileuser like '%" + WebUtility.InputText(tbshopfileuser.Text) + "%'";

        }

        switch (this.ddlisdelivercash.SelectedValue)
        {
            case "1":
                SqlWhere += " and ( settlecycle =0 or (settlecycle = 1 and OrderSums <> 0) or systemuserid=1 )";


                break;
            default:
                break;
        }

     
        WebUtility.FixsetCookie("SearchOrderSqlWhere", SqlWhere, 1);
    }


    protected void btSearch_Click(object sender, EventArgs e)
    {
        initsql();
        BindData(ordersort);
    }


    protected void rtpOrderlist_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        string type = e.CommandName;
        switch (type)
        {
            case "isauth":
                authOrder("Unid=" + e.CommandArgument);
                break;
            case "isfile":
                fileOrder("Unid=" + e.CommandArgument);
                break;
        }
    }

    protected void DelList_Click(object sender, EventArgs e)
    {
        //判断权限
        int _rs = WebUtility.checkOperator(4);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('无操作权限','success','true',5);init();");
            return;
        }
        string IdList = this.hdDels.Value;
        if (bll.DelList(IdList,UserHelp.GetAdmin().AdminName) > 0)
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "tipsWindown('提示信息','text:删除成功!','250','150','true','1000','true','text');init();");
            BindData(ordersort);
        }
        else
        {
            AlertScript.RegScript(this.Page, this.UpdatePanel1, "tipsWindown('提示信息','text:删除失败!','250','150','true','1000','true','text');init();");
        }
    }


    protected void ot(object sender, EventArgs e)
    {
        ordersort = "OrderDateTime";//custorder.OrderDateTime
        BindData(ordersort);
    }

    protected void os(object sender, EventArgs e)
    {
        ordersort = "OrderStatus";
        BindData(ordersort);
    }

    /// <summary>
    /// 翻页事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindData(ordersort);
    }


    protected void btExport_Click(object sender, EventArgs e)
    {
        initsql();
        //判断权限
        int _rs = WebUtility.checkOperator(5);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, "alert('无操作权限','success','true',5);init();");
            return;
        }
        Response.Redirect("shopsettleExcel.aspx?type=1");
    }

    protected void partExport_Click(object sender, EventArgs e)
    {
        //判断权限
        int _rs = WebUtility.checkOperator_super(7);
        if (_rs == 0)
        {
            AlertScript.RegScript(this.Page, UpdatePanel1,"alert('无操作权限','success','true',5);init();");
            return;
        }
        string IdList = this.hdDels.Value;
        WebUtility.FixsetCookie("SearchOrderSqlWhere", "Custorder.unid in (" + IdList + ")", 1);

        Response.Redirect("shopsettleExcel.aspx?type=1");
    }

    /// <summary>
    /// 批量审核
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void allauth_Click(object sender, EventArgs e)
    {
        authOrder(SqlWhere);
    }

    /// <summary>
    /// 批量归档
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void allfile_Click(object sender, EventArgs e)
    {
        fileOrder(SqlWhere);
    }

    /// <summary>
    /// 批量审核
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void partauth_Click(object sender, EventArgs e)
    {
        string IdList = this.hdDels.Value;
        authOrder("unid in ("+IdList+")");
    }

    /// <summary>
    /// 批量归档
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void partfile_Click(object sender, EventArgs e)
    {
        string IdList = this.hdDels.Value;
        fileOrder("unid in (" + IdList + ")");
    }


    public void authOrder(string were)
    {
        string sql = "UPDATE dbo.Custorder SET Commentstate = 1, shopauthuser = '" + UserHelp.GetAdmin().AdminName+ " " + DateTime.Now.ToShortTimeString() + "' WHERE " + were + " and Commentstate = 0";
        WebUtility.excutesql(sql);
        BindData("");

        AlertScript.RegScript(this.Page, this.UpdatePanel1, "tipsWindown('提示信息','text:设置成功!','250','150','true','2000','true','text');init();");
    }

    /// <summary>
    /// 结清
    /// </summary>
    /// <param name="were"></param>
    protected void fileOrder(string were)
    {
        string sql = "UPDATE dbo.Custorder SET pointrat = 1, shopfileuser = '" + UserHelp.GetAdmin().AdminName + " " + DateTime.Now.ToShortTimeString() + "',settledate = getdate() WHERE " + were + " and pointrat = 0";
        WebUtility.excutesql(sql);
        BindData("");

        AlertScript.RegScript(this.Page, this.UpdatePanel1, "tipsWindown('提示信息','text:设置成功!','250','150','true','2000','true','text');init();");

    }

}
